package controller

import (
	"TTMS/dao"
	"TTMS/model"
	"TTMS/utils"
	"fmt"
	"html/template"
	"net/http"
	"strconv"
	"time"
)

// ToBuyTicket 买电影票
func ToBuyTicket(w http.ResponseWriter, r *http.Request) {
	//判断是否登录
	sess, flag := dao.IsLogin(r)
	if !flag {
		//未登录
		sess = &model.Session{}
	} //已登录
	sess.IsLogin = flag
	//获取电影名称
	filmName := r.FormValue("filmName")
	//根据电影名称获取电影
	sess.NowFilm = dao.CheckFilmByName(filmName)
	time1 := time.Now()
	time2 := time1.Add(time.Hour * 24)
	time3 := time2.Add(time.Hour * 24)
	sess.Dates[0] = fmt.Sprintf("今天 %02d月%02d日", time1.Month(), time1.Day())
	sess.Dates[1] = fmt.Sprintf("明天 %02d月%02d日", time2.Month(), time2.Day())
	sess.Dates[2] = fmt.Sprintf("后天 %02d月%02d日", time3.Month(), time3.Day())
	//获取日期
	date := r.FormValue("date")
	if date == "" {
		sess.Date = sess.Dates[0]
		date = fmt.Sprintf("%d-%02d-%02d", time1.Year(), time1.Month(), time1.Day())
	} else {
		sess.Date = date
		date = strconv.Itoa(time1.Year()) + "-" + date[7:9] + "-" + date[12:14]
	}
	//根据日期获取演出计划
	sess.Schedules, _ = dao.GetSchedulesByDateAndFilmName(date, filmName)
	//解析模版
	t := template.Must(template.ParseFiles("views/pages/film/buy_ticket.html"))
	//执行
	t.Execute(w, sess)
}

// SeatPage 前往选座购票页面
func SeatPage(w http.ResponseWriter, r *http.Request) {
	//判断是否登录
	sess, flag := dao.IsLogin(r)
	if !flag {
		//未登录
		//前往登录页面
		Login(w, r)
		return
	}
	sess.IsLogin = flag
	//获取演出计划的id
	scheduleID, _ := strconv.ParseInt(r.FormValue("scheduleID"), 10, 0)
	//根据演出计划的ID获取座位信息
	sess.Seats, _ = dao.GetSeats(scheduleID)
	//根据演出计划ID获取演出计划
	sess.Schedule = dao.GetSchedulesByID(scheduleID)
	//解析模版
	t := template.Must(template.ParseFiles("views/pages/film/seat.html"))
	//执行
	t.Execute(w, sess)
}

// ToOrderPage 前往订单页面
func ToOrderPage(w http.ResponseWriter, r *http.Request) {
	//获取 sess
	sess, _ := dao.IsLogin(r)
	//创建订单编号
	orderID := utils.CreateUUID()
	//获取座位id
	r.ParseForm()
	seatsID := r.Form["seat"]
	var seats []*model.Seat
	for _, v := range seatsID {
		//将 v 转换为 int64 类型
		id, _ := strconv.ParseInt(v, 10, 0)
		//根据座位ID查询座位
		seat := dao.GetSeatByID(id)
		//修改座位状态
		dao.UpdateSeatByID(seat.ID, orderID, 2)
		go dao.UpdateSeatByStateIS2(seat.ID)
		go dao.UpdateOrderWait(orderID, 2)
		seats = append(seats, seat)
	}
	//获取演出计划的ID
	scheduleID, _ := strconv.ParseInt(r.FormValue("scheduleID"), 10, 0)
	//根据演出计划的ID获取演出计划
	schedule := dao.GetSchedulesByID(scheduleID)
	order := &model.Order{
		OrderID:    orderID,
		Seats:      seats,
		UserID:     sess.UserID,
		CreateTime: time.Now().Format("2006-01-02 15:04:05"),
		State:      0,
		Price:      schedule.Price,
		User:       sess.User,
		FilmName:   schedule.FilmName,
		HallID:     schedule.HallID,
		ScheduleID: scheduleID,
		TotalCount: int64(len(seats)),
	}
	order.TotalAmount = float64(order.TotalCount) * order.Price
	//将订单添加到数据库中
	_ = dao.AddOrder(order)
	//解析模版
	t := template.Must(template.ParseFiles("views/pages/film/order.html"))
	//执行
	t.Execute(w, order)
}

// ToTicketPage 前往票的界面
func ToTicketPage(w http.ResponseWriter, r *http.Request) {
	//获取 sess
	sess, _ := dao.IsLogin(r)
	//获取订单编号
	orderID := r.FormValue("orderID")
	//根据订单编号更新订单的状态
	dao.UpdateOrder(orderID, 1)
	//根据订单编号获取更新过后的订单信息
	order := dao.GetOrder(orderID)
	//获取座位信息
	cols := r.FormValue("cols")
	rows := r.FormValue("rows")
	seatIDs := r.FormValue("seatIDs")
	//更新座位状态
	for i, v := range seatIDs {
		if i%2 != 0 {
			dao.UpdateSeatByID(int64(v), orderID, 1)
		}
	}
	//根据演出计划的ID获取演出计划
	schedule := dao.GetSchedulesByID(order.ScheduleID)
	//根据电影名称获取电影信息
	film := dao.GetFilmsByName(order.FilmName)
	film.Sales += order.TotalCount
	film.TicketOffice += float64(film.Sales) * order.Price
	//更新电影销量和票房信息
	dao.UpdateFilm(film)
	var tickets []*model.Ticket
	for i, v := range cols {
		if i%2 != 0 {
			ticket := &model.Ticket{
				OrderID:   orderID,
				FilmName:  order.FilmName,
				Col:       int64(v),
				Row:       int64(rows[i]),
				StartTime: schedule.StartTime,
				EndTime:   schedule.EndTime,
				Price:     order.Price,
				OrderTime: order.CreateTime,
				State:     0,
				UserID:    sess.UserID,
				Date:      schedule.Date,
			}
			//将票添加到数据库中
			ticket, _ = dao.AddTicket(ticket)
			tickets = append(tickets, ticket)
		}
	}
	sess.Tickets = tickets
	//解析模版
	t := template.Must(template.ParseFiles("views/pages/film/ticket.html"))
	t.Execute(w, sess)
}

// ToMyOrdersPage 前往我的订单页面
func ToMyOrdersPage(w http.ResponseWriter, r *http.Request) {
	//获取 sess
	sess, _ := dao.IsLogin(r)
	//根据用户ID获取订单
	orders, _ := dao.GetOrdersByUserID(sess.UserID)
	sess.Orders = orders
	//解析模版
	t := template.Must(template.ParseFiles("views/pages/film/my_orders.html"))
	//执行
	t.Execute(w, sess)
}

// ToMyTicketsPage 前往我的电影票界面
func ToMyTicketsPage(w http.ResponseWriter, r *http.Request) {
	//获取 sess
	sess, _ := dao.IsLogin(r)
	//根据用户ID获取电影票
	tickets, _ := dao.GetTicketsByUserID(sess.UserID)
	sess.Tickets = tickets
	//解析模版
	t := template.Must(template.ParseFiles("views/pages/film/my_tickets.html"))
	//执行
	t.Execute(w, sess)
}
